<?php
$con = mysql_connect("192.168.0.17","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("faithwar", $con);
date_default_timezone_set("PRC"); //timezone
#$dateTime = date("Y-m-d",strtotime("-2 day"));
$dateTime = date("Y-m-d");
#$dateTime = '2012-03-28';

mysql_query("TRUNCATE TABLE faithwar.tbheartbeat_last");
mysql_query("TRUNCATE TABLE faithwar.tbheartbeat_last_temp");
  //insert
 mysql_query("INSERT INTO  tbheartbeat_last
   SELECT max(logDate),
   date,
   logInfo,
   cities,
   crystal,
   deviceid
 FROM  tbheartbeat
 WHERE date = '$dateTime'
 GROUP BY deviceid"); 

$deviceid_query = mysql_query("select  DISTINCT deviceid from tbheartbeat where date='$dateTime'"); //id select  DISTINCT deviceid,date,logInfo,crystal,max(logDate) from tbheartbeat
while($deviceid = mysql_fetch_array($deviceid_query))
{

//Calculation TC value
    $tc_query = mysql_query("SELECT crystal
        FROM tbheartbeat
        WHERE `deviceid` = '$deviceid[deviceid]'
        AND date = '$dateTime'
        ORDER BY `logDate` DESC
        LIMIT 1  ");
    $tc = mysql_fetch_array($tc_query);
      # code...
      //update
  $sql = "UPDATE  tbheartbeat_last SET crystal= '$tc[crystal]' WHERE deviceid= '$deviceid[deviceid]'";

   if(mysql_query($sql,$con)){
    echo "1 update is ok!";
} else {
    echo "failed".mysql_error();
}
   


} 
mysql_close($con);
?>